package com.danceforyou.common.controller;

import com.danceforyou.common.model.ConfigDO;
import com.danceforyou.common.restful.exception.BizExceptionEnum;
import com.danceforyou.common.service.ConfigService;
import com.danceforyou.common.util.AssertUtil;
import com.danceforyou.common.util.Constants;
import com.danceforyou.common.vo.ConfigVO;
import com.danceforyou.user.model.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 类名称：ConfigController
 * 创建人：danceforyou
 * 创建时间：2020年04月15日
 * 版本号：1.0v
 */
@RestController
@RequestMapping(value="/config")
public class ConfigController {

    @Autowired
    private ConfigService configService;
	@Autowired(required = false)
	private HttpSession session;

	/**
	 * 获取系统配置信息
	 * @return List<Config>
	 */
	@RequestMapping(value = "getSysConfig", method = RequestMethod.GET)
	public List<ConfigDO> getSysConfig() {
		UserDO loginUser = (UserDO) session.getAttribute(Constants.SESSION_USER);
		AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
		return configService.listAll();
	}

	/**
	 * 保存系统配置信息
	 * @return boolean
	 */
	@RequestMapping(value = "saveConfig", method = RequestMethod.POST)
	public boolean saveConfig(@RequestParam Map<String, String> configMap) {
		configService.saveConfig(configMap);
		return true;
	}

	/**
	 * 根据配置项获取配置信息
	 * @param text 配置项
	 * @return Config
	 */
	@RequestMapping(value = "/getConfigByText", method = RequestMethod.GET)
	public ConfigDO getConfigByText(String text) {
		UserDO loginUser = (UserDO) session.getAttribute(Constants.SESSION_USER);
		AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
		ConfigDO config = configService.getByProperty("configText", text);
		if (config == null) {
			config = new ConfigDO();
			config.setConfigText(text);
			switch (text) {
				case Constants.CONFIG_SHOW_RANK:
					config.setConfigValue("1");
					break;
				case Constants.CONFIG_PRECISE_TAX:
					config.setConfigValue("1");
					break;
				case Constants.CONFIG_SUPERVISOR_ALL:
					config.setConfigValue("0");
					break;
				case Constants.CONFIG_CUSTOMER_VALID_DAY:
					config.setConfigValue("60");
					break;
				case Constants.CONFIG_IP_WHITE_LIST:
					config.setConfigValue("");
					break;
				case Constants.CONFIG_MAX_LOGIN_FAILED_NUMBER:
					config.setConfigValue("5");
					break;
			}
		}
		return config;
	}
}
